package servlet;

import entity.User;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        String nickname = request.getParameter("nickname");
        byte gender = Byte.parseByte(request.getParameter("gender"));
        String idCard = request.getParameter("idCard");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        byte userType = Byte.parseByte(request.getParameter("userType"));
        String openId = request.getParameter("openId");

        if (!password.equals(confirmPassword)) {
            response.sendRedirect("register.jsp?error=true");
            return;
        }

        User newUser = new User();
        newUser.setAccount(account);
        newUser.setPassword(password);
        newUser.setNickname(nickname);
        newUser.setGender(gender);
        newUser.setIdCard(idCard);
        newUser.setEmail(email);
        newUser.setPhone(phone);
        newUser.setType(userType);
        newUser.setOpenId(openId);

        // 调用UserService进行注册
        UserService userService = new UserService();
        boolean registered = userService.register(newUser);

        if (registered) {
            response.sendRedirect("login.jsp");
        } else {
            response.sendRedirect("register.jsp?error=true");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
